package com.shadow.demo.info.controller;

import cn.hutool.core.text.StrBuilder;
import com.shadow.demo.common.constants.SysConstants;
import com.shadow.demo.common.info.IPTypeEnum;
import com.shadow.demo.data.info.entity.IpInfoEntity;
import com.shadow.demo.info.service.IpInfoService;
import com.shadow.demo.info.service.SiteService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

import java.text.SimpleDateFormat;
import java.util.Objects;
import java.util.stream.IntStream;

@Slf4j
@Controller
public class InfoPageController {

    private final SiteService siteService;
    private final IpInfoService ipInfoService;

    InfoPageController(SiteService siteService, IpInfoService ipInfoService) {
        this.siteService = siteService;
        this.ipInfoService = ipInfoService;
    }

    @GetMapping("public/site/index")
    public String siteIndex() {
        return "modules/site/index";
    }

    @GetMapping("/site/list")
    public String siteList() {
        return "modules/site/list";
    }

    @GetMapping("/site/add")
    public String siteAdd() {
        return "modules/site/add";
    }

    @GetMapping("/site/edit/{id}")
    public String siteEdit(@PathVariable("id") String id, final ModelMap model) {
        model.put("entity", siteService.getById(id));
        return "modules/site/edit";
    }

    @RequiresPermissions("info:ip:home")
    @GetMapping("/ip/home")
    public String homeIP(final ModelMap model) {
        IpInfoEntity latestData = ipInfoService.getLatestData(IPTypeEnum.REMOTE_HOME.getType(), null);
        model.put(SysConstants.S_DATA, getIPString(latestData));
        return "sys/index";
    }

    @RequiresPermissions("info:ip:690")
    @GetMapping("/ip/690")
    public String iP690(final ModelMap model) {
        IpInfoEntity latestData = ipInfoService.getLatestData(IPTypeEnum.LOCAL_690.getType(), null);
        model.put(SysConstants.S_DATA, getIPString(latestData));
        return "sys/index";
    }

    private String getIPString(final IpInfoEntity latestData) {
        if (Objects.isNull(latestData)) {
            return StringUtils.EMPTY;
        }
        StrBuilder str = new StrBuilder();
        str.append(latestData.getIpAddress().replace(",", "<br />"));
        IntStream.range(0, 8).forEach(x -> str.append("<br />"));
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        str.append(formatter.format(latestData.getAddDate()));
        return str.toString();
    }
}
